//
//  MCAudioStreamRead.m
//  MCSimpleAudioPlayerDemo
//
//  Created by carl on 16/1/9.
//  Copyright © 2016年 Chengyin. All rights reserved.
//

#import "MCAudioStreamRead.h"
#import "MCAudioFileStream.h"

#define kAQDefaultBufSize 1024

@interface MCAudioStreamRead ()
{
    NSURL* _url;
    CFReadStreamRef stream;
    NSDictionary *httpHeaders;
    NSInteger fileLength;
    NSInteger seekByteOffset;
}
@end

@implementation MCAudioStreamRead

static void ASReadStreamCallBack
(
 CFReadStreamRef aStream,
 CFStreamEventType eventType,
 void* inClientInfo
 )
{
    MCAudioStreamRead* streamRead = (__bridge MCAudioStreamRead *)inClientInfo;
    [streamRead handleReadFromStream:aStream eventType:eventType];
}

- (instancetype)initWithUrl:(NSURL* )url
{
    if(self = [super init]){
        _url = url;
    }
    return self;
}

- (BOOL)openReadStream
{
    CFHTTPMessageRef message= CFHTTPMessageCreateRequest(NULL, (CFStringRef)@"GET", (__bridge CFURLRef)_url, kCFHTTPVersion1_1);
    stream = CFReadStreamCreateForHTTPRequest(NULL, message);
    CFRelease(message);
    if(CFReadStreamSetProperty(
                               stream,
                               kCFStreamPropertyHTTPShouldAutoredirect,
                               kCFBooleanTrue)){
        NSLog(@"set fail");
        return NO;
    }
    CFDictionaryRef proxySettings = CFNetworkCopySystemProxySettings();
    CFReadStreamSetProperty(stream, kCFStreamPropertyHTTPProxy, proxySettings);
    CFRelease(proxySettings);
    
    if([[_url scheme] isEqualToString:@"https"])
    {
        NSDictionary *sslSettings =
        [NSDictionary dictionaryWithObjectsAndKeys:
         (NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL, kCFStreamSSLLevel,
         [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
         [NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredRoots,
         [NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
         [NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
         [NSNull null], kCFStreamSSLPeerName,
         nil];
        
        CFReadStreamSetProperty(stream, kCFStreamPropertySSLSettings, (__bridge CFTypeRef)(sslSettings));
    }
    //open
    if (!CFReadStreamOpen(stream))
    {
        CFRelease(stream);
        NSLog(@"open fail");
        return NO;
    }
    CFStreamClientContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};
    CFReadStreamSetClient(
                          stream,
                          kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
                          ASReadStreamCallBack,
                          &context);
    CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    return YES;
}

- (void)handleReadFromStream:(CFReadStreamRef)aStream
                   eventType:(CFStreamEventType)eventType
{
    if (aStream != stream)return;
    if(eventType == kCFStreamEventHasBytesAvailable){
        UInt8 bytes[kAQDefaultBufSize];
        CFIndex length;
        @synchronized(self){
            length = CFReadStreamRead(stream, bytes, kAQDefaultBufSize);
            if(length == -1){
                NSLog(@"读取长度失败");
                return;
            }
            if(length == 0)return;
        }
    }
}

@end
